package cn.tedu.redisson.controller;

import org.redisson.api.RLock;
import org.redisson.api.RMapCache;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

@RestController
public class CouponController {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RedissonClient redissonClient;
    @GetMapping("coupons")
    public String doBuyCoupon(HttpServletRequest request){

        String key="coupon:a";
        RLock lock = redissonClient.getLock(key);
        try {
            if (lock.tryLock(10, 5, TimeUnit.SECONDS)) {
                String ip = request.getRemoteAddr();
                RMapCache<Object, Object> users = redissonClient.getMapCache("users");
                if(users.containsKey(ip))
                    throw new RuntimeException("请勿重复购买");
                Long result = redisTemplate.opsForValue().decrement("counter");
                if (result < 0) {
                    return "抢购失败";
                }
                users.put(ip, "1", 5, TimeUnit.MINUTES);
                return "请购成功";
            }else{
                return "继续努力";
            }
        }catch (InterruptedException e){
            e.printStackTrace();
            return "抢购失败";
        }finally {
            lock.unlock();
        }
    }
}
